<template>
    <div class="role-manage-container">
        <!-- 搜索条件框 -->
        <div class="search-area">
            <el-input v-model="searchRoleName" placeholder="请输入角色名称" style="width: 200px;"></el-input>
            <el-select v-model="searchIsValid" placeholder="请选择是否有效" style="width: 200px;">
                <el-option label="有效" value="1" />
                <el-option label="无效" value="0" />
            </el-select>
            <el-button @click="searchRoles" type="primary" icon="el-icon-search" style="width: 10%;">搜索</el-button>
            <el-button @click="resetSearch" type="info" icon="el-icon-delete" style="width: 10%;">重置</el-button>
        </div>

        <!-- 新增按钮区域 -->
        <div class="add-role-area">
            <el-button @click="openDialog('add')" type="success" icon="el-icon-plus"
                style="width: 10%;">新增角色</el-button>
        </div>

        <!-- 列表展示 -->
        <el-table :data="roleList" stripe border>
            <el-table-column prop="roleName" label="角色名称" width="150"></el-table-column>
            <el-table-column prop="roleDesc" label="角色描述" width="600"></el-table-column>
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button @click="openDialog('detail', scope.row)" type="success" icon="el-icon-view"
                        style="width: 100px; text-align: center;">查看详情</el-button>
                    <el-button @click="openDialog('edit', scope.row)" type="warning" icon="el-icon-edit"
                        style="width: 100px; text-align: center;">修改角色</el-button>
                    <el-button @click="deleteRole(scope.row.roleId)" type="danger" icon="el-icon-delete"
                        style="width: 100px; text-align: center;">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
            :page-sizes="[10, 20, 30]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
            :total="total"></el-pagination>

        <!-- 新增、修改、详情 -->
        <el-dialog :visible.sync="dialogVisible" :title="dialogTitle" custom-class="add-role-dialog"
            :show-close="false">
            <el-form :model="formRole" ref="formRole" label-width="120px" :disabled="dialogMode === 'detail'">
                <el-form-item label="角色名称">
                    <el-input v-model="formRole.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述">
                    <el-input v-model="formRole.roleDesc"></el-input>
                </el-form-item>
                <el-form-item label="是否有效">
                    <el-select v-model="formRole.isValid">
                        <el-option label="是" value="1" />
                        <el-option label="否" value="0" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button v-if="dialogMode !== 'detail'" @click="submitRole" type="primary">确定</el-button>
                    <el-button @click="dialogVisible = false" type="danger">关闭</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import axios from 'axios';

export default {
    data() {
        return {
            // 搜索条件
            searchRoleName: '',
            searchIsValid: '1',
            // 分页参数
            currentPage: 1,
            pageSize: 10,
            total: 0,
            // 列表对象
            roleList: [],
            // 弹窗相关参数
            dialogVisible: false,
            dialogMode: '',
            dialogTitle: '',
            formRole: {
                roleId: null,
                roleName: '',
                roleDesc: '',
                isValid: '1'
            }
        }
    },
    methods: {
        // 列表查询
        searchRoles() {
            axios.get('http://localhost:8080/shopping/role/list', {
                params: {
                    roleName: this.searchRoleName,
                    isValid: this.searchIsValid,
                    currentPage: this.currentPage,
                    pageSize: this.pageSize
                }
            }).then(response => {
                this.roleList = response.data.data.records;
                this.total = response.data.total;
            }).catch(error => {
                console.error('搜索角色失败:', error);
            })
        },
        // 重置搜索条件
        resetSearch() {
            this.searchRoleName = '';
            this.searchIsValid = '1';
            this.currentPage = 1;
            this.searchRoles();
        },

        // 获取所有菜单
        fetchMenus() {
            axios.get('http://localhost:8080/shopping/menu/all').then(response => {
                this.menuList = response.data.data;
                this.cascaderMenus = this.formatMenuTree(this.menuList);
            }).catch(error => {
                console.error('获取菜单失败:', error);
            });
        },

        openDialog(mode, role = null) {
            this.dialogMode = mode;
            this.dialogVisible = true;
            this.fetchMenus(); // 打开弹窗时获取菜单
            if (mode === 'add') {
                this.dialogTitle = '新增角色';
                this.formRole = {
                    roleId: null,
                    roleName: '',
                    roleDesc: '',
                    isValid: '1',
                    menuIds: []
                }
            } else {
                this.dialogTitle = mode === 'edit' ? '编辑角色' : '查看详情';
                this.formRole = {
                    ...role,
                    isValid: role.isValid.toString(),
                    menuIds: role.menuIds || []
                }
            }
        },
        submitRole() {
            const payload = {
                ...this.formRole,
                isValid: parseInt(this.formRole.isValid),
                menuIds: this.formRole.menuIds // 传递菜单ID数组
            }
            const method = this.dialogMode === 'edit' ? 'put' : 'post';
            const url = this.dialogMode === 'edit' ? 'http://localhost:8080/shopping/role/edit' : 'http://localhost:8080/shopping/role/add';
            axios[method](url, payload).then(response => {
                if (response.data.code === 200) {
                    this.$message.success(`${this.dialogMode === 'edit' ? '修改' : '新增'}角色成功`);
                    this.dialogVisible = false;
                    this.searchRoles();
                } else {
                    this.$message.error(`${this.dialogMode === 'edit' ? '修改' : '新增'}角色失败：${response.data.message}`)
                }
            }).catch(error => {
                console.error(`${this.dialogMode === 'edit' ? '修改' : '新增'}角色失败:`, error);
                this.$message.error(`${this.dialogMode === 'edit' ? '修改' : '新增'}角色失败，请检查网络`);
            })
        },

        deleteRole(roleId) {
            this.$confirm('确定要删除该角色吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                axios.delete('http://localhost:8080/shopping/role/del', {
                    params: { roleId }
                }).then(response => {
                    if (response.data.code === 200) {
                        this.$message.success('删除角色成功');
                        this.searchRoles();
                    } else {
                        this.$message.error('删除角色失败:' + response.data.message);
                    }
                }).catch(error => {
                    console.error('删除角色失败:', error);
                    this.$message.error('删除角色失败，请检查网络');
                });
            }).catch(() => {
                this.$message.info('已取消删除');
            });
        },

        // 每页数量变化
        handleSizeChange(newSize) {
            this.pageSize = newSize;
            this.searchRoles();
        },
        // 当前页码变化
        handleCurrentChange(newPage) {
            this.currentPage = newPage;
            this.searchRoles();
        }
    },
    mounted() {
        this.searchRoles();
    }
}
</script>

<style scoped>
.role-manage-container {
    padding: 20px;
}

.search-area {
    margin-bottom: 10px;
    display: flex;
    align-items: center;
    gap: 10px;
}

.search-area .el-input {
    margin-right: 10px;
}

.search-area .el-select {
    margin-right: 10px;
}

.search-area .el-button {
    margin-right: 10px;
}


.el-button {
    height: 40px;
    margin-top: -12px;
}

.add-role-area {
    margin-bottom: 20px;
}

.el-table {
    margin-bottom: 20px;
}

.add-role-dialog {
    width: 500px;

    .el-dialog__header {
        background-color: #f0f9eb;
        border-bottom: 1px solid #e5e5e5;
        padding: 15px;
    }

    .el-dialog__title {
        color: #67c23a;
        font-size: 18px;
    }

    .el-dialog__body {
        padding: 20px;
    }

    .el-dialog__footer {
        border-top: 1px solid #e5e5e5;
        padding: 15px;
        text-align: right;
    }
}
</style>